package com.yuan.aiagent.controller;

import com.yuan.aiagent.app.CodeApp;
import io.reactivex.Emitter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/ai")
public class AFSIMController {

    @Autowired
    CodeApp codeApp;
    @GetMapping("query")
    public String AFSIMQuery(@RequestParam String question) {
        System.out.println("用户:"+question);
        String uuid = UUID.randomUUID().toString();
        try {
            String answer = codeApp.doChatWithRange(question, uuid);
            System.out.println("AI:"+answer);
            return answer;
        } catch (Exception e) {
            System.err.println("处理请求时发生错误: " + e.getMessage());
            e.printStackTrace();
            return "服务器内部错误，请稍后再试";
        }
    }

    @GetMapping("/chat/sse_emitter")
    public SseEmitter doChatEmitter(String message,String chatId) {
        SseEmitter emitter = new SseEmitter();
        codeApp.doChatByStream(message,chatId)
                .subscribe(chunk->{
                    try {
                        emitter.send(chunk);
                    }catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                },emitter::completeWithError,emitter::complete);
        return emitter;
    }
}
